//////////////////////////////////////////////////////////////////////////////
//
// File: buff.h
//  
// Description:
//   This class helps to manage a buffer object that is basically an
//   malloc-ed area of memory managed by a pointer.
//    
// How it works:
//   This class is basically a buffer of data held by a unsigned char* data 
//   pointer.  Within this buffer lies possibly many packets.  Packets are
//   a chunk of data prepared in a fashion that complies with the bnet
//   protocol.  Packets contain a header consisting of a 0xFF (u8 byte),
//   packet ID ( u8 byte), and size of the packet (short int).  In this whole
//   thing, two 'size' values are manazed.  The 'unsigned short sz' value
//   is the size of the whole buffer and whatever packets it may contain.
//   The 'unsigned short packetSz' is the size of the current packet
//   we are on/dealing with.  When data is extracted from the buffer,
//   both sizes are decremented by the appropriate amount.
//

#ifndef BUFF_H
#define BUFF_H

#include<fstream>
#include<sys/time.h>
#include "types.h"
using namespace std;


string print_hex_form(u8 x);
string print_hex_form(u32 x);


class buff {

 public:
  buff();
  ~buff();
  bool add(const void* toAdd, int bytes);  // appends to the end of buff
  void clear();
  short size();
  void* getPtr();
  void setPacketID(u8 newID);    // set and get packetID
  u8 getPacketID();
  void setPacketSz(unsigned short newSz);
  unsigned short getPacketSz();
  bool package();   // get the buffer ready to be sent.
  bool strip();     // strip the header info off and leave just the data.
  bool extract(u8 &stuff);   // extract from the front of the buffer.
  bool extract(u16 &stuff);
  bool extract(u32 &stuff);
  bool extract(u64 &stuff);
  bool extract(string &stuff);
  bool extract(char *stuff);

  void print_buffer();

 private:
  unsigned char* data;
  unsigned short sz;   // Number of bytes left in the buffer.
  unsigned short packetSz;  // Number of bytes left in buffer for the
                            //   current packet
  
  u8 packetID;     
  u8 startByte;    // This is used to store the 0xFF byte (that means nothing)
};

#endif


// End of   buff.h

